//
//  RSATool.swift
//  CloudNews
//
//  Created by macos on 2018/4/11.
//  Copyright © 2018年 macos. All rights reserved.
//

import UIKit
import GTMBase64

class RSATool: NSObject {

    static var share = RSATool.init()
    private override init() {
    }
    
    
    
    
    let pub_key = "自家公钥字符串"
    
    let pri_key = "自家私钥字符串"
    
    
    
    lazy var  rsaCryptor:BBRSACryptor = {
        let rsa =  BBRSACryptor.init();
        return rsa;
    }()
    
    
    ///公钥加密
    func Rsa_encod(encodeStr:String) {
        
        rsaCryptor.importRSAPublicKeyBase64(pub_key);
        
        let enData = encodeStr.data(using: String.Encoding.utf8);
        
        let rsaData = rsaCryptor.encryptWithPublicKey(usingPadding: RSA_PADDING_TYPE.PKCS1, plainData: enData);
        
        let base64Str = GTMBase64.string(byEncoding: rsaData);
        
        print(base64Str ?? "加密失败!");
        
        Rsa_decode(decodeStr: base64Str ?? "");
    }
    
    ///私钥解密
    func Rsa_decode(decodeStr:String) {
       
        rsaCryptor.importRSAPrivateKeyBase64(pri_key);

        let endata64 = decodeStr.data(using: String.Encoding.utf8);
        let data64 = GTMBase64.decode(endata64);
        let data = rsaCryptor.decryptWithPrivateKey(usingPadding: RSA_PADDING_TYPE.PKCS1, cipherData: data64);
        let destr = String.init(data: data!, encoding: String.Encoding.utf8);
        
        print("解密结果=,\(destr)");
    }
    
    
}
